//
//  KCustomSlideViewController.m
//  NeiHan
//
//  Created by Kevin on 2017/3/16.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KCustomSlideViewController.h"

@interface KCustomSlideViewController ()<UIScrollViewDelegate>

@property(nonatomic,weak)UIScrollView* scrollView;
@property(nonatomic,strong)NSMutableDictionary* displayVCs;
@property(nonatomic,strong)NSMutableDictionary* memoryCache;
@property(nonatomic,assign)NSInteger currentIndex;
@property(nonatomic,weak)UIViewController* currentViewController;

@end

@implementation KCustomSlideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(UIScrollView *)scrollView{
    if (!_scrollView) {
        UIScrollView* scroll = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:scroll];
        scroll.delegate = self;
        scroll.showsVerticalScrollIndicator = NO;
        scroll.showsHorizontalScrollIndicator = NO;
        scroll.pagingEnabled = YES;
        scroll.bounces = YES;
        _scrollView = scroll;
    }
    return _scrollView;
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.scrollView.frame = self.view.bounds;
    //根据子控制器的数量，配置scrollView的contentSize
    self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*[self numberOfChildViewControllers], self.scrollView.frame.size.height);
}

-(NSMutableDictionary *)memoryCache{
    if (!_memoryCache) {
        _memoryCache = [[NSMutableDictionary alloc]init];
    }
    return _memoryCache;
}
-(NSMutableDictionary *)displayVCs{
    if (!_displayVCs) {
        _displayVCs = [[NSMutableDictionary alloc]init];
    }
    return _displayVCs;
}

-(void)setSelectedIndex:(NSInteger)selectedIndex{
    _selectedIndex = selectedIndex;
    //[self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width*selectedIndex, 0) animated:YES];
    [self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.frame.size.width*selectedIndex, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) animated:NO];
}

//移除控制器
-(void)removeChildViewController:(UIViewController*)childViewController atIndex:(NSInteger)index{
    
    if (childViewController == nil) return;
    
    //当前显示删除、放入缓存中
    [childViewController.view removeFromSuperview];
    [childViewController willMoveToParentViewController:nil];
    [childViewController removeFromParentViewController];
    
    [self.displayVCs removeObjectForKey:@(index)];
    if (![self.memoryCache objectForKey:@(index)]) {
        [self.memoryCache setObject:childViewController forKey:@(index)];
    }
}

-(void)reloadData{
    [self.memoryCache removeAllObjects];
    [self.displayVCs removeAllObjects];
    
    for (NSInteger index = 0; index < self.childViewControllers.count; index ++) {
        UIViewController* viewController = self.childViewControllers[index];
        [viewController.view removeFromSuperview];
        [viewController willMoveToParentViewController:nil];
        [viewController removeFromParentViewController];
    }
    
    self.scrollView.frame = self.view.bounds;
    self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*[self numberOfChildViewControllers], self.scrollView.frame.size.height);
    [self scrollViewDidScroll:self.scrollView];
}

//保存并显示当前控制器
-(void)addChildViewController:(UIViewController *)childController atIndex:(NSInteger)index{
    if ([self.childViewControllers containsObject:childController]) {
        return;
    }
    //添加控制器并放入正在显示的控制器中
    [self addChildViewController:childController];
    [self.displayVCs setObject:childController forKey:@(index)];
    [childController didMoveToParentViewController:self];
    [self.scrollView addSubview:childController.view];
    childController.view.frame = CGRectMake(index * self.view.bounds.size.width, 0, self.view.bounds.size.width, self.view.bounds.size.height);
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger currentPage = scrollView.contentOffset.x/self.scrollView.frame.size.width;
    if (scrollView.isDragging) {
        return;
    }
    //获取当前控制器
    UIViewController* viewController = [self.displayVCs objectForKey:@(currentPage)];
    if (viewController == nil) {
        [self initializedViewControllerAtIndex:currentPage];
    }
    
    //将其他控制器移除，防止继续播放音视频
    /*
     for (NSInteger index = 0; index < [self numberOfChildViewControllers]; index++) {
     if (currentPage != index) {
     UIViewController* viewController = [self.displayVCs objectForKey:@(index)];
     [self removeChildViewController:viewController atIndex:index];
     }
     }
     */
    
    if ([self.delegate respondsToSelector:@selector(customSlideViewController:slideIndex:)]) {
        [self.delegate customSlideViewController:self slideIndex:currentPage];
    }
}
/*
 -(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
 if ([self.delegate respondsToSelector:@selector(customSlideViewController:slideOffset:)]) {
 [self.delegate customSlideViewController:self slideOffset:scrollView.contentOffset];
 }
 }
 */
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSInteger currentPage = scrollView.contentOffset.x/self.scrollView.frame.size.width;
    if (scrollView.contentOffset.x <= 0) {
        return;
    }else if (scrollView.contentOffset.x >= scrollView.contentSize.width-scrollView.width) {
        return;
    }else{
        if (currentPage == self.selectedIndex) {
            currentPage += 1;
        }
        
        UIViewController* viewController = [self.displayVCs objectForKey:@(currentPage)];
        if (viewController == nil) {
            [self initializedViewControllerAtIndex:currentPage];
        }
        if ([self.delegate respondsToSelector:@selector(customSlideViewController:slideIndex:)]) {
            [self.delegate customSlideViewController:self slideIndex:currentPage];
        }
        _selectedIndex = currentPage;
    }
}

-(void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
}
/*
 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
 if ([self.delegate respondsToSelector:@selector(customSlideViewController:slideIndex:)]) {
 [self.delegate customSlideViewController:self slideIndex:scrollView.contentOffset.x / scrollView.frame.size.width];
 }
 
 }
 */



#pragma mark - DataSource

/**
 获取当前控制器:1.从缓存中获取;2.从代理中获取并放入缓存中

 @param index 当前控制器索引值
 */
-(void)initializedViewControllerAtIndex:(NSInteger)index{
    //从缓存中获取控制器
    UIViewController* viewController = [self.memoryCache objectForKey:@(index)];
    if (viewController == nil) {
        if ([self.dataSource respondsToSelector:@selector(slideViewController:viewControllerAtIndex:)]) {
            viewController = [self.dataSource slideViewController:self viewControllerAtIndex:index];
            [self addChildViewController:viewController atIndex:index];
        }
    }else{
        [self addChildViewController:viewController atIndex:index];
    }
}

//
/**
 获取子控制器的数量

 */
-(NSInteger)numberOfChildViewControllers{
    if ([self.dataSource respondsToSelector:@selector(numberOfChildViewControllersInSlideViewController:)]) {
        return [self.dataSource numberOfChildViewControllersInSlideViewController:self];
    }
    return 0;
}


@end
